package com.winterchen.exception;

import com.winterchen.model.error.ErrorInfo;
import com.winterchen.utils.LogUtils;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @className GlobalExceptionHandler
 * @Description 统一异常处理器
 * @Author Administrator
 * @Date 2018/9/12 0012 16:45
 * @Version 1.0
 **/
@ControllerAdvice
public class GlobalExceptionHandler {
    // 默认错误页面
    private static final String DEFAUL_ERROR_PAGE = "error";
    // 这个方法是返回错误页面
    /*@ExceptionHandler(Exception.class)
    public ModelAndView defaulErrorHandler(HttpServletRequest request, Exception e) throws Exception{
        ModelAndView mav = new ModelAndView();
        mav.addObject("Exception:",e);
        mav.addObject("url","请求路径: " + request.getRequestURI());
        mav.setViewName(DEFAUL_ERROR_PAGE);
        return mav;
    }*/

    /**
     * @ExceptionHandler 匹配抛出自定义的异常类型 MyException
     * ErrorInfo 为自定义的一个数据封装类，用于返回的json数据
     * 如果返回的是json格式，需要加上@ResponsBody
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ErrorInfo jsonErrorHandler(HttpServletRequest request,Exception e) throws Exception {
        Logger log = LogUtils.getExceptionLogger();
        log.error("异常信息:" + e.getMessage() + " url: " + request.getRequestURI());
        return ErrorInfo.err(e.getMessage(),request.getRequestURI(),"操作失败");
    }


}
